package com.example.administrator.printoutindemo.mvp.ui.activity;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.printoutindemo.OutStorageList;
import com.example.administrator.printoutindemo.OutStorageMaterialCheckList;
import com.example.administrator.printoutindemo.R;
import com.example.administrator.printoutindemo.StoreOutStorageCheckList2Adapter;
import com.example.administrator.printoutindemo.services.Tools;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.List;

import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import com.jess.arms.base.BaseConstants;


public class DaiShenPiXiangQingActivity extends AppCompatActivity {

    private static final String WEBSERVICE_CONFIG = "TEXT";
    private static final int LOGINSUCCESS = 0;
    private static final int NETWORKERROR = 2;
    private static final int SYSERROR = 3;
    private static final int UPLOADSUCCESS = 4;
    private EditText s_cl_act2_shyj = null;
    private Button store_cl_act2_btn_yes = null;
    private Button store_cl_act2_btn_no = null;
    private ListView store_cl_act2_listView = null;
    private StoreOutStorageCheckList2Adapter adapter = null;
    private OutStorageMaterialCheckList oli = null;
    private List<OutStorageMaterialCheckList> li_oli = null;
    private OutStorageList outStorageList = null;
    private String SYSException = "";
    private SharedPreferences sPreferencces;
    private int user_id;
    private TextView tv_xiang_mu_ming_cheng = null;
    private TextView tv_xiang_mu_bian_hao = null;
    private TextView tv_shen_he_zhuang_tai = null;
    @SuppressLint("HandlerLeak")
    private final Handler hanlder = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case LOGINSUCCESS:

                    adapter.setList(li_oli);
                    store_cl_act2_listView.setAdapter(adapter);
                    tv_xiang_mu_ming_cheng.setText(li_oli.get(0).get_projectname());
                    tv_xiang_mu_bian_hao.setText(li_oli.get(0).getProid());
                    tv_shen_he_zhuang_tai.setText(li_oli.get(0).getCheck_status());
                    LoadingDialogUtil.dismissDialog();
                    break;

                case NETWORKERROR:

                    Toast.makeText(DaiShenPiXiangQingActivity.this,
                            "网络或系统异常!", Toast.LENGTH_LONG).show();
                    LoadingDialogUtil.dismissDialog();

                    break;
                case SYSERROR:

                    Toast.makeText(DaiShenPiXiangQingActivity.this,
                            "系统异常!" + SYSException, Toast.LENGTH_LONG).show();
                    LoadingDialogUtil.dismissDialog();

                    break;
                case UPLOADSUCCESS:

                    Toast.makeText(DaiShenPiXiangQingActivity.this, "审核成功！",
                            Toast.LENGTH_LONG).show();

                    finish();
//                    Intent in = new Intent();
//                    in.setClass(StoreOutStorageCheckList2Activity.this, StoreOutStorageCheckList1Activity.class);
//                    startActivity(in);

                    LoadingDialogUtil.dismissDialog();

                    break;

                default:
                    LoadingDialogUtil.dismissDialog();

                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dai_shen_pi_xiang_qing);
        ToolbarUtils.initToolbarTitleBack(this, "详情");
        sPreferencces = getSharedPreferences(WEBSERVICE_CONFIG, 0);
        store_cl_act2_btn_yes = (Button) findViewById(R.id.store_cl_act2_btn_yes);
        store_cl_act2_btn_no = (Button) findViewById(R.id.store_cl_act2_btn_no);
        tv_xiang_mu_ming_cheng = (TextView) findViewById(R.id.tv_xiang_mu_ming_cheng);
        tv_xiang_mu_bian_hao = (TextView) findViewById(R.id.tv_xiang_mu_bian_hao);
        tv_shen_he_zhuang_tai = (TextView) findViewById(R.id.tv_shen_he_zhuang_tai);
        store_cl_act2_listView = (ListView) findViewById(R.id.store_cl_act2_listView);
        View mFooter = LayoutInflater.from(this).inflate(R.layout.include_shen_he_yi_jian, null);  //加载footer的布局
        s_cl_act2_shyj = (EditText) mFooter.findViewById(R.id.s_cl_act2_shyj);
//        store_cl_act2_listView.addFooterView(mFooter);
        adapter = new StoreOutStorageCheckList2Adapter(this);
        oli = new OutStorageMaterialCheckList();
        outStorageList = new OutStorageList();
//		final int user_id = ((dyjApplication) getApplication()).get_user_id();// 审核人ID
        user_id = Integer.parseInt(sPreferencces.getString(BaseConstants.UID, ""));//审核人ID

        store_cl_act2_btn_yes.setOnClickListener(new store_cl_act2_btn_yes_click());
        store_cl_act2_btn_no.setOnClickListener(new store_cl_act2_btn_no_click());

        if (user_id != 0) {

            new Thread(new Runnable() {

                @Override
                public void run() {

                    try {
                        String out_storagelist_batchid = getIntent()
                                .getStringExtra("outCheckProject");
                        li_oli = callWebServiceGetMaterialInfo(out_storagelist_batchid);

                        if (li_oli != null) {
                            Message m = new Message();
                            m.what = DaiShenPiXiangQingActivity.LOGINSUCCESS;
                            hanlder.sendMessage(m);
                        }

                    } catch (Exception e) {
                        Message m = new Message();
                        m.what = DaiShenPiXiangQingActivity.SYSERROR;
                        hanlder.sendMessage(m);
                    }

                }
            }).start();
        } else {
            Tools.showDialogInfo(this, "登录已过期，请重新登录");
        }

    }

    // 获取审核物料清单列表
    private List<OutStorageMaterialCheckList> callWebServiceGetMaterialInfo(
            String out_storagelist_batchid) {

        LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);
        List<OutStorageMaterialCheckList> result = null;

        try {

            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://dyjapp.org/";
            String methodName = "GetCheckMaterial";


            String url = "http://" + sPreferencces.getString(BaseConstants.IP, "") + ":"
                    + sPreferencces.getString(BaseConstants.PORT, "")
                    + "/StoreService.asmx";

            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            request.addProperty("out_storagelist_batchid",
                    out_storagelist_batchid);
            // request.addProperty("check_user_id", check_user_id);
            // request.addProperty("check_status", "未审核");

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            if (envelope.getResponse() != null) {
                SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
                // if ("1".equals(response.toString())) {
                String t = response.toString();

                if (!t.equals("")) {
                    result = oli.getListFromJSON(t);
                }

            }
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            // TODO: handle exception
            LoadingDialogUtil.dismissDialog();

            SYSException = e.toString();
        }

        return result;
    }

    // 更改清单审核状态
    private boolean uploadWebService(List<OutStorageList> li) {

        boolean bl = false;

        for (int i = 0; i < li.size(); i++) {
            OutStorageList n = li.get(i);
            String jsonStr = outStorageList.ConvertToJson(n);

            try {

                /****************** 调用webService ***********************/
                // 调用.net 的WebService.
                String nameSpace = "http://dyjapp.org/";
                String methodName = "UpdateOutStorageList";


                String url = "http://" + sPreferencces.getString(BaseConstants.IP, "") + ":"
                        + sPreferencces.getString(BaseConstants.PORT, "")
                        + "/StoreService.asmx";
                // // 10.0.2.2
                // 为Android模拟器的本地(localhost)IP
                String soapAction = nameSpace + methodName;

                // 设置连接参数
                SoapObject request = new SoapObject(nameSpace, methodName);

                // 增加属性参数。 将相关的函数参数放入到过程中。
                request.addProperty("modelJson", jsonStr);

                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                        SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
                // V1.1）;

                // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
                // 不指定rpc方式则用true否则要用false
                envelope.dotNet = true;

                // envelope.setOutputSoapObject(request);//设置请求参数
                envelope.bodyOut = request; // enveloper.bodyOut=request 与
                // envelope.setOutputSoapObject(request)
                // 效果相同。
                // step4 创建HttpTransportSE对象
                HttpTransportSE ht = new HttpTransportSE(url);
                // step5 调用WebService
                ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
                if (envelope.getResponse() != null) {
                    SoapPrimitive response = (SoapPrimitive) envelope
                            .getResponse();
                    if (!("0".equals(response.toString()))) {
                        // int id = Integer.parseInt(response.toString());
                        bl = true;
                    }
                }
                /****************** 调用webService结束 ***********************/

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        return bl;
    }

    // 审核通过
    private void callCheckAgree(String dpid, String reason, int person_id) {

        try {

            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://dyjapp.org/";
            String methodName = "CheckAgree";


            String url = "http://" + sPreferencces.getString(BaseConstants.IP, "") + ":"
                    + sPreferencces.getString(BaseConstants.PORT, "")
                    + "/StoreService.asmx";
            // // 10.0.2.2
            // 为Android模拟器的本地(localhost)IP
            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            request.addProperty("dpid", dpid);
            request.addProperty("reason", reason);
            request.addProperty("person_id", person_id);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 审核不通过
    private void callCheckDisagree(String dpid, String reason, int person_id) {

        try {

            /****************** 调用webService ***********************/
            // 调用.net 的WebService.
            String nameSpace = "http://dyjapp.org/";
            String methodName = "CheckDisagree";


            String url = "http://" + sPreferencces.getString(BaseConstants.IP, "") + ":"
                    + sPreferencces.getString(BaseConstants.PORT, "")
                    + "/StoreService.asmx";
            // // 10.0.2.2
            // 为Android模拟器的本地(localhost)IP
            String soapAction = nameSpace + methodName;

            // 设置连接参数
            SoapObject request = new SoapObject(nameSpace, methodName);

            // 增加属性参数。 将相关的函数参数放入到过程中。
            request.addProperty("dpid", dpid);
            request.addProperty("reason", reason);
            request.addProperty("person_id", person_id);

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
            // V1.1）;

            // 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
            // 不指定rpc方式则用true否则要用false
            envelope.dotNet = true;

            // envelope.setOutputSoapObject(request);//设置请求参数
            envelope.bodyOut = request; // enveloper.bodyOut=request 与
            // envelope.setOutputSoapObject(request)
            // 效果相同。
            // step4 创建HttpTransportSE对象
            HttpTransportSE ht = new HttpTransportSE(url);
            // step5 调用WebService
            ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
            /****************** 调用webService结束 ***********************/

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 审核通过
    private class store_cl_act2_btn_yes_click implements OnClickListener {
        @Override
        public void onClick(View v) {

            if (li_oli.size() > 0) {


                new Thread(new Runnable() {

                    @Override
                    public void run() {

                        try {

                            String out_storagelist_batchid = li_oli.get(0).get_out_storagelist_batchid();
                            String shyj = s_cl_act2_shyj.getText().toString();// 审核意见

                            callCheckAgree(out_storagelist_batchid, shyj, user_id);

                            Message m = new Message();
                            m.what = DaiShenPiXiangQingActivity.UPLOADSUCCESS;
                            hanlder.sendMessage(m);

                        } catch (Exception e) {
                            Message m = new Message();
                            m.what = DaiShenPiXiangQingActivity.SYSERROR;
                            hanlder.sendMessage(m);
                        }

                    }
                }).start();

            }

        }
    }

    // 审核未通过
    private class store_cl_act2_btn_no_click implements OnClickListener {
        @Override
        public void onClick(View v) {
            if (li_oli.size() > 0) {

//				final List<OutStorageList> li_osl = new ArrayList<OutStorageList>();
//
//				String shyj = s_cl_act2_shyj.getText().toString();// 审核意见
//
//				for (OutStorageMaterialCheckList o : li_oli) {
//
//					String out_storageList_id = o.get_out_storageList_id();// 出库申请单ID
//
//					OutStorageList os = new OutStorageList();
//
//					os.set_check_status("审核未通过");
//					os.set_check_reason(shyj);
//					os.set_out_storageList_id(Integer
//							.parseInt(out_storageList_id));
//
//					li_osl.add(os);
//
//				}

                new Thread(new Runnable() {

                    @Override
                    public void run() {

                        try {

//							boolean b = uploadWebService(li_osl);
//
//							if (b) {
//								Message m = new Message();
//								m.what = StoreOutStorageCheckList2Activity.UPLOADSUCCESS;
//								hanlder.sendMessage(m);
//							}

                            String out_storagelist_batchid = li_oli.get(0).get_out_storagelist_batchid();
                            String shyj = s_cl_act2_shyj.getText().toString();// 审核意见
//                            int user_id = ((dyjApplication) getApplication()).get_user_id();// 物料员ID

                            callCheckDisagree(out_storagelist_batchid, shyj,
                                    user_id);

                            Message m = new Message();
                            m.what = DaiShenPiXiangQingActivity.UPLOADSUCCESS;
                            hanlder.sendMessage(m);

                        } catch (Exception e) {
                            Message m = new Message();
                            m.what = DaiShenPiXiangQingActivity.SYSERROR;
                            hanlder.sendMessage(m);
                        }

                    }
                }).start();

            }
        }
    }
}